<template>
   <div class="login-page">
      <el-card class="box-card">
         <div slot="header" class="clearfix"></div>
         <div class="login-form">
            <!-- 登陆表单 -->
            <el-form v-if="!isRegister" :model="user" :rules="loginRules">
               <el-form-item prop="userName">
                  <el-input v-model="user.userName" auto-complete="off" placeholder="请输入用户名" type="text">
                     <template slot="prepend"><i class="el-icon-s-custom" style="font-size:20px"></i></template>
                  </el-input>
               </el-form-item>

               <el-form-item prop="password">
                  <el-input v-model="user.password" auto-complete="off" placeholder="请输入密码" type="password">
                     <template slot="prepend"><i class="el-icon-key" style="font-size:20px"></i></template>
                  </el-input>
               </el-form-item>

               <template slot="prepend"><i class="el-icon-s-check" style="font-size:20px"></i></template>

               <el-form-item>
                  <el-button style="width:100%;" type="primary" @click="handleLogin">登录</el-button>
               </el-form-item>

               <el-form-item class="flex">
                  <el-link :underline="false" type="info" @click="RegisterchangeMsg(), clearuser()">
                     注册 →
                  </el-link>
               </el-form-item>
            </el-form>

            <!-- 注册表单 -->
            <el-form v-if="isRegister" :model="user" :rules="loginRules">
               <div class="parent-image">
                  <el-form-item prop="avatar">
                     <el-upload :before-upload="beforeAvatarUpload" :on-success="addhandleAvatarSuccess"
                        :show-file-list="false" action="http://localhost:8080/user/avatar/upload"
                        class="avatar-uploader">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                     </el-upload>
                  </el-form-item>
               </div>
               <el-form-item prop="userName">
                  <el-input v-model="user.userName" auto-complete="off" placeholder="请输入用户名" type="text">
                     <template slot="prepend"><i class="el-icon-s-custom" style="font-size:20px"></i></template>
                  </el-input>
               </el-form-item>
               <el-form-item prop="realName">
                  <el-input v-model="user.realName" auto-complete="off" placeholder="请输入真实姓名" type="text">
                     <template slot="prepend"><i class="el-icon-postcard" style="font-size:20px"></i></template>
                  </el-input>
               </el-form-item>
               <el-form-item prop="phone">
                  <el-input v-model="user.phone" auto-complete="off" placeholder="联系电话" type="text">
                     <template slot="prepend"><i class="el-icon-phone" style="font-size:20px"></i></template>
                  </el-input>
               </el-form-item>

               <el-form-item prop="password">
                  <el-input v-model="user.password" auto-complete="off" placeholder="请输入密码" type="password">
                     <template slot="prepend"><i class="el-icon-key" style="font-size:20px"></i></template>
                  </el-input>
               </el-form-item>

               <el-form-item>
                  <el-button style="width:100%;" type="success" @click="register">注册</el-button>
               </el-form-item>

               <el-form-item class="flex">
                  <el-link :underline="false" type="info" @click="LoginchangeMsg(), clearuser()">
                     ← 返回
                  </el-link>
               </el-form-item>

            </el-form>

         </div>
      </el-card>
   </div>
</template>

<script>
import request from '@/utils/request';
export default {
   data() {
      return {
         imageUrl: '',
         //表单验证
         isRegister: false,
         user: {
            userId: '',
            userName: '',
            password: '',
            avart: '',
            roleName: '',
            realName: '',
            phone: ''
         },
         loginRules: {
            userName: [
               { validator: this.checkUsername, trigger: 'blur' },
            ],
            password: [
               { validator: this.checkPassword, trigger: 'blur' },

            ],
            realName: [
               { validator: this.checkRealname, trigger: 'blur' },

            ],
            phone: [
               { validator: this.checkPhone, trigger: 'blur' },

            ]
         }
      }
   },
   methods: {
      addhandleAvatarSuccess(res, file) {
         this.imageUrl = URL.createObjectURL(file.raw);
         this.user.avart = res.data
      },

      beforeAvatarUpload(file) {
         const isJPG = file.type === 'image/jpeg';
         const isLt2M = file.size / 1024 / 1024 < 2;

         if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
         }
         if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
         }
         return isJPG && isLt2M;
      },
      //登录
      // async handleLogin() {
      //    try {
      //       const res = await request.post('/user/login',this.user);
      //       console.log(res.data.code)
      //       console.log(res.data.message)
      //       console.log(res.data)
      //       // 假设后端返回的状态码为200表示成功，且数据结构包含code和message
      //       if (res.data.code == '0') {
      //          localStorage.setItem("user",JSON.stringify(res.data));//存储用户信息到浏览器
      //          this.$router.push('/index'); // 跳转到主页或其他受保护的页面
      //          this.$message({
      //             message: '登录成功',
      //             type: 'success'
      //          });
      //       } else {
      //          // 登录失败，显示错误信息
      //          this.$message({
      //             message: res.data.message,
      //             type: 'error'
      //          });
      //       }
      //    } catch (error) {
      //       // 网络错误或其他异常
      //       console.error('登录时发生错误:', error);
      //       this.$message({
      //          message: '登录时发生错误，请重试',
      //          type: 'error'
      //       });
      //    }
      // },
      handleLogin() {
         request.post("/user/login", this.user).then(res => {
            if (res.data.code == "0") {
               localStorage.setItem("user", JSON.stringify(res.data));//存储用户信息到浏览器
               this.$router.push('/index'); // 跳转到主页或其他受保护的页面
               this.$message.success("登陆成功")
            } else {
               this.$message.error("用户名或密码错误")
            }
         }).catch(error => {
            console.log(new error("服务异常"))
            this.$message.error("服务异常")
         })
      },
      //注册
      register() {
         if(this.user.avart== null){
            this.$message.error("未上传头像")
         }else{
              request.post("/user/register", this.user).then(res => {
            if (res.data.code == '0') {
               this.$message.success("注册成功，可以进行账号登录!")
            } else {
               this.$message.error(res.data.message)
            }
         }).catch(error => {
            console.log(new error("服务异常"))
            this.$message.error("服务异常")
         })
         }
      },
      //校验用户名
      checkUsername(rule, value, callback) {
         if (!value) {
            // 明确调用callback以处理错误情况
            callback(new Error('用户名不能为空'));
         } else {
            // 直接进行长度验证，无需setTimeout
            if (value.length < 5 || value.length > 15) {
               callback(new Error('用户名长度应为5~15个字符'));
            } else {
               // 如果验证通过，也需要调用callback，表示验证完成且无错误
               callback();
            }
         }
      },
      //校验密码
      checkPassword(rule, value, callback) {
         if (!value) {
            // 明确调用callback以处理错误情况
            callback(new Error('密码不能为空'));
         } else {
            // 直接进行长度验证，无需setTimeout
            if (value.length < 5 || value.length > 15) {
               callback(new Error('密码长度应为5~15个字符'));
            } else {
               // 如果验证通过，也需要调用callback，表示验证完成且无错误
               callback();
            }
         }
      },
      //校验真实姓名
      checkRealname(rule, value, callback) {
         if (!value) {
            // 明确调用callback以处理错误情况
            callback(new Error('真实姓名不能为空'));
         } else {
            // 直接进行长度验证，无需setTimeout
            if (value.length < 0 || value.length > 5) {
               callback(new Error('真实姓名长度应为0~5个字符'));
            } else {
               // 如果验证通过，也需要调用callback，表示验证完成且无错误
               callback();
            }
         }
      },
      //校验用户名
      checkPhone(rule, value, callback) {
         if (!value) {
            // 明确调用callback以处理错误情况
            callback(new Error('电话不能为空'));
         } else {
            // 直接进行长度验证，无需setTimeout
            if (value.length != 11) {
               callback(new Error('电话长度应为11个数字'));
            } else {
               // 如果验证通过，也需要调用callback，表示验证完成且无错误
               callback();
            }
         }
      },
      //注册表单切换提醒
      RegisterchangeMsg() {
         this.isRegister = true
         this.$message({
            message: '注册切换成功',
            type: 'success'
         })
      },
      //返回登陆表单切换提醒信息
      LoginchangeMsg() {
         this.isRegister = false
         this.$message({
            message: '返回登陆成功',
            type: 'success'
         })
      },
      //清理切换表单的残留数据
      clearuser() {
         this.user = {
            userName: '',
            password: '',
            roleName: ''
         }
      }

   }


}
</script>

<style lang="less" scoped>
.parent-image {
   display: flex;
   justify-content: center;
   align-items: center;
   height: 100%;
   /* 根据需要调整高度 */
}

/* 头像上传样式 */
.avatar-uploader .el-upload {
   border: 2px dashed #100f0f;
   border-radius: 100%;
   cursor: pointer;
   position: relative;
   overflow: hidden;
}

.avatar-uploader .el-upload:hover {
   border-color: #409EFF;
}

.avatar-uploader-icon {
   font-size: 28px;
   color: #8c939d;
   width: 80px;
   height: 80px;
   line-height: 80px;
   text-align: center;
}

.avatar {
   width: 80px;
   height: 80px;
   display: block;
}

.login-page {
   /* background:whitesmoke; */
   background: url('@/assets/backgroud.png') no-repeat center / cover;
   ;
   height: 100vh;
   display: flex;
   justify-content: center;
   align-items: center;
}

.clearfix {

   width: 100%;
   height: 60px;
   background: url('@/assets/logo.png') no-repeat center / cover;
   ;
   /* background: red; */

}
</style>